<template>
  <div class="hello">
    <ul>
      <li v-for="(item, index) in orderList" :key="index">
        <div>
          {{ item.comment }}
        </div>
        <div>
          {{ item.time | dateFormate() }}
        </div>
      </li>
    </ul>
    <input type="text" v-model="comment" /><button @click="addComment()">
      提交评论
    </button>
  </div>
</template>

<script>
import { request } from '../utits/request.js'
export default {
  name: 'Home',
  data() {
    return {
      commentList: [],
      comment: ''
    }
  },
  methods: {
    async getList() {
      let { data: list } = await request({
        url: 'http://146.56.230.35:3001/commentList',
        method: 'get'
      })
      this.commentList = list
      console.log(list)
    },
    async addComment() {
      let obj = {
        comment: this.comment,
        time: new Date()
      }
      let { data: res } = await request({
        url: 'http://146.56.230.35:3001/commentList',
        method: 'post',
        data: obj
      })
      console.log(res)
      this.comment = ''
      this.getList()
    }
  },
  created() {
    this.getList()
  },
  computed: {
    //根据时间的倒序排序
    orderList() {
      let list = JSON.parse(JSON.stringify(this.commentList))
      let n = list.length
      for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
          let date1 = +new Date(list[j].time) //1
          let date2 = +new Date(list[j + 1].time) //2
          if (date1 < date2) {
            let t = list[j]
            list[j] = list[j + 1]
            list[j + 1] = t
          }
        }
      }
      console.log(list)
      return list
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less"></style>
